<script setup lang="ts">
import { onMounted, watch, ref } from "@vue/runtime-core";
import { useI18n } from "vue-i18n";
import { useThemeConfig } from "@/store/modules/themeConfig";
import { valueAndLabel } from "@/global/interface";
import { local } from "@/utils";
import { GlobalI18n } from "@/global/const";
const { locale } = useI18n()
const storeTheme = useThemeConfig()
const lang = ref('')

const options = [
  {
    value: 'zh-cn',
    label: '中文',
  },
  {
    value: 'en',
    label: 'English',
  },
]

watch(lang, (val, oldVal) => {
  if (val === oldVal) return
  locale.value = val
  storeTheme.setGlobalI18n(val)
  local.set(GlobalI18n, val)
  if(val !== oldVal && oldVal) history.go(0)
})

onMounted(() => {
  try {
    const globalI18n = local.get(GlobalI18n)
    if (globalI18n) {
      lang.value = globalI18n
    } else {
      lang.value = options.find((p: valueAndLabel) => p.value === window.navigator.language)?.value || 'zh-cn'
    }
  }
  catch (err) {
    lang.value = options.find((p: valueAndLabel) => p.value === window.navigator.language)?.value || 'zh-cn'
  }
})

</script>

<template>
  <el-select v-model="lang" placeholder="Select" class="select-width" size="small">
    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
  </el-select>
</template>

<style scoped lang="less">
.select-width{
  width: 100px !important;
}
</style>